import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login'
import Home from '@/components/Home'
import Welcome from '@/components/Welcome'
import User from '@/components/user/User'
import Right from '@/components/permission/Right'
import Role from '@/components/permission/Role'
import Category from '@/components/good/Category'
import Param from '@/components/good/Param'
import Good from '@/components/good/Good'
import Add from '@/components/good/Add'
import Order from '@/components/order/Order'
import Report from '@/components/report/Report'
Vue.use(VueRouter)

const router = new VueRouter({
  // path 监听地址
  routes: [
    // 重定向路由规则 redirect重定向
    { path: '/', redirect: '/login' },
    // component使用组件
    { path: '/login', component: Login },
    // 访问home 重定向到welcome
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: User },
        { path: '/rights', component: Right },
        { path: '/roles', component: Role },
        { path: '/categories', component: Category },
        { path: '/params', component: Param },
        { path: '/goods', component: Good },
        { path: '/goods/add', component: Add },
        { path: '/orders', component: Order },
        { path: '/reports', component: Report }
      ]
    }
  ]
})

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 挂载路由导航守卫 参数是回调函数
router.beforeEach((to, from, next) => {
  // to是将要访问的路径
  // from是从哪个路径跳转来
  // next()表示放行 next('/xxx')强制跳转
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

// 暴露出去
export default router
